Page({
  data: {
    promises: [], // 回复列表数据
    courseId: null,        // 课程ID
    replyStates: new Map(),
    subActive: 0,         // 当前激活的子标签索引
    loadedDiscussions: [],// 讨论列表数据
    courseId: null,       // 课程 ID（需从页面参数获取）
    currentSort: 'time_asc' ,// 当前排序方式
    isFavorited: false, 
    isShowAll:false,
    isCollapsed:true,
    active: 0,
    value: 2,
    
    course: {  
      id: null,
      course_name: '',
      video_file_name: '',
      total_duration: '',
      image: '',
      original_price: 0,
      current_price: 0,
      intro: '',
      target_audience: '',
      learning_outcomes: '',
      subscription_note: '',
      consultant_id: null,
      study_count: 0,
      collection_count: 0,
      review_count: 0,
      material_count: 0,
      validity_period: 0,
      publish_time: '',
      category_id: null
    },
    // 评论相关数据
    reviews: [],
    displayReviews: [],
    isShowAll: false
  },
  handleBack() {
    // 方法 1：返回上一页（可指定返回层数）
    wx.navigateBack({
      delta: 1 // 返回的页面层数，默认 1（返回上一层）
    });

    // 方法 2：等价于 wx.navigateBack()（简洁写法）
    // wx.navigateBack();
  },
  onLoad(options) {
    const courseId = options.id||1;
    this.setData({ courseId }); 
    this.fetchData11();
    Promise.all([
      this.fetchCourseData(courseId),
      this.fetchReviews(courseId),
    
    ]).then(([courseRes, reviewsRes,Discuss,]) => {
      console.log(courseRes,reviewsRes)
      if (courseRes.statusCode === 200 && reviewsRes.statusCode === 200) {
        this.processCourseResponse(courseRes.data.data);


        reviewsRes.data.forEach((item)=>{
          item.reviewTime = new Date(item.reviewTime).getTime();
          item.abc=this.formatTime123(item.reviewTime);
          console.log("=11111111111111111111111111",item.reviewTime)
        })
        this.processReviewsResponse(reviewsRes.data);

      }
    }).catch(err => {
      console.error('请求失败:', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
    });
  },
  // 收藏
  handleFavorite() {
    const courseId = this.data.courseId;
    const isFavorited = this.data.isFavorited;
    const action = isFavorited ? 'remove' : 'add';
    this.preUpdateUI(action); 
    wx.request({
      url: `http://localhost:8080/zh/course/favorite/${courseId}`,
      method: 'POST',
      data: { action },
      success: (res) => {
        if (res.statusCode === 200) {
          this.confirmFinalState(res.data);
          wx.showToast({
            title: action === 'add' ? '收藏成功' : '取消收藏',
            icon: 'success'
          });
        } else {
          this.rollbackState(); 
        }
      },
      
      fail: () => {
        this.rollbackState(); 
      }
    });
  },
  preUpdateUI(action) {
    const newCount = this.data.course.collection_count + 
      (action === 'add' ? 1 : -1);
    
    this.setData({
      isFavorited: !this.data.isFavorited,
      [`course.collection_count`]: newCount
    });
  },
  confirmFinalState(res) {
    this.setData({
      [`course.collection_count`]: res.data.newCollectionCount
    });
  },
  rollbackState() {
    const originalAction = this.data.isFavorited ? 'remove' : 'add';
    this.preUpdateUI(originalAction); 
    wx.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  },
  fetchCourseData(courseId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/zh/course/${courseId}`,
        success: resolve,
        fail: reject
      });
    });
  },
  fetchReviews(courseId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `http://localhost:8080/zh/courseReview/${courseId}`,
        data: { courseId },
        success: resolve,
        fail: reject
      });
    });
  },
  onSubTabChange(e) {
    const index = e.detail.index;
    const sortMap = ['time_asc', 'time_desc', 'count_desc'];
    
    this.setData({
      subActive: index,
      currentSort: sortMap[index]
    }, () => {
      this.fetchData11();
    });
  },
   // 数据请求核心方法
   fetchData11() {
    let timerId = null; // 新增定时器 ID
    
    // 设置延迟显示 Loading 的定时器
    timerId = setTimeout(() => {
      wx.showLoading({ title: '加载中...' });
    }, 1000);

    
    wx.request({
      url: `http://localhost:8080/zh/courseDiscussion/byCourse/${this.data.courseId}/nullPromise`,
      data: { sort: this.data.currentSort },
      success: (res) => {
        clearTimeout(timerId);
        wx.hideLoading(); 
        const formattedData11 = res.data.data.map(item => ({
          ...item,
          formattedTime11: this.formatTime11(item.discussionTime),
          discussionPromiseCount: item.discussionPromiseCount || 0
        }));
        
        this.setData({ loadedDiscussions: formattedData11 });
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
      },
      complete: () => wx.hideLoading()
    });
  },

 
  formatTime11(timestamp) {
    const date = new Date(timestamp);
    return `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
  },

  toggleCollapse11(e) {
    const { id, discussions } = e.currentTarget.dataset;
    const targetItem = this.data.loadedDiscussions.find(item => item.id === id);
    const isCollapsed = !targetItem.isCollapsed;
    
    this.setData({
      [`loadedDiscussions[${this.data.loadedDiscussions.findIndex(item => item.id === id)}].isCollapsed`]: isCollapsed
    });
  },

  // 处理课程数据
  processCourseResponse(rawData) {
    const formattedData = {
      ...rawData,
      course_name: rawData.courseName,
      video_file_name: rawData.videoFileName,
      image: rawData.image,
      original_price: Number(rawData.originalPrice).toFixed(2),
      current_price: Number(rawData.currentPrice).toFixed(2),
      intro: rawData.intro,
      target_audience: rawData.targetAudience,
      learning_outcomes: rawData.learningOutcomes,
      subscription_note: rawData.subscriptionNote,
      consultant_id: rawData.consultantId,
      study_count: Number(rawData.studyCount),
      collection_count: Number(rawData.collectionCount),
      review_count: Number(rawData.reviewCount),
      material_count: Number(rawData.materialCount),
      validity_period: rawData.validityPeriod,
      category_id: rawData.categoryId,
      publish_time: this.formatDate(rawData.shangXianTime),
      total_duration: this.formatDuration(rawData.totalDuration)

    };
    
    this.setData({
      course: formattedData,
      isPurchased: this.checkPurchaseStatus(formattedData.id)
    });
  },

  // 处理评论数据
  processReviewsResponse(rawData) {
    const formattedData = rawData.map(item => {
      const reviewTime = new Date(item.reviewTime).getTime(); // 转换为时间戳
      return {
        ...item,
        userName: item.userId || '匿名用户',
        reviewTime: reviewTime
      };
    });
    this.setData({ reviews: formattedData });
  
  
    
    this.setData({
      reviews: formattedData,
      displayReviews: formattedData.slice(0, 5)
    });
  },


// 处理回复
  processPromisesResponse(rawData) {
    const formattedData = rawData.map(item => {
      return {
        ...item,
        isCollapsed:false
      };
    });
    this.setData({ Promises: formattedData });
    console.log(Promises,"==========!!!!!!!!!!!!!");
  },

  formatDate(timestamp) {
    
    const date = new Date(timestamp);
  
    return `${date.getFullYear()}-${this.pad(date.getMonth()+1)}-${this.pad(date.getDate())}`;
  },
  formatTime123(stimestamp) {
   console.log('000000000000000000000')
    const now = new Date()
    const diff = now - stimestamp
    console.log('======================',diff)
    const units = [
      { unit: '天', div: 86400000 },
      { unit: '小时', div: 3600000 },
      { unit: '分钟', div: 60000 },
      { unit: '秒', div: 1000 }
    ]
    for (const { unit, div } of units) {
      if (diff >= div) {
        const val = Math.floor(diff / div)
        return `${val}${unit}前`
      }
    }
    return '刚刚'
  },


  formatDuration(timeString) {
    const timeParts = timeString.split(':');
    const hours = timeParts[0] || '00';
    const minutes = timeParts[1] || '00';
    return `${hours.padStart(2, '0')}小时${minutes.padStart(2, '0')}分`;
  },

  pad(num) {
    return num < 10 ? `0${num}` : num;
  },


  toggleShowAll() {
    this.setData({
      isShowAll: !this.data.isShowAll,
      displayReviews: !this.data.isShowAll 
        ? this.data.reviews.slice(0, 5) 
        : this.data.reviews
    });
  },
  getIndexById(id) {
    return this.data.loadedDiscussions.findIndex(item => item.id === id);
    },
   // 新增 toggleCollapse 函数
toggleCollapse(e) {
  const discussionId = e.currentTarget.dataset.id;
  const index = this.getIndexById(discussionId);
  const courseId = this.data.courseId;
  const discussion = this.data.loadedDiscussions[index];
      if(!discussion.isCollapsed){
  wx.request({
    url: `http://localhost:8080/zh/courseDiscussion/byCourse/${courseId}/promise/${discussionId}`,
    success: (res) => {
      wx.hideLoading();
      if (res.data.code === 200) {
        // 将返回的promises数据存入对应讨论项
        this.setData({
          [`loadedDiscussions[${index}].promises`]: res.data.data
        
        });
        console.log("&7777777777777777",this.data.promises)
      }
    },
    fail: (err) => {
      wx.hideLoading();
      console.error('获取回复失败:', err);
     
      this.setData({
        isCollapsed: true
      });
    }
  })
};
  this.setData({
    [`loadedDiscussions[${index}].isCollapsed`]: discussion.isCollapsed === null  ? true : !discussion.isCollapsed
  });
console.log(index,"111111111111",this.data.loadedDiscussions[index].isCollapsed)
  if (discussion.isCollapsed) {

    let timerId = null; // 新增定时器 ID
      // 设置延迟显示 Loading 的定时器
      timerId = setTimeout(() => {
        wx.showLoading({ title: '加载中...' });
      }, 1000);
      clearTimeout(timerId);                                                 
  }
},
  
  checkPurchaseStatus(courseId) {
    const purchased = wx.getStorageSync('purchased_courses') || [14,23,24,27,11,29];
    return purchased.includes(Number(courseId));
  }
});